﻿using System;
using System.Collections.Generic;
using Generator.Selections.DataBase;
using Generator.Selections.DataDictionary;

namespace Generator.Selections.Repository
{
    class ColumnRepository
    {
        internal List<Column> GetColumns(string tableName)
        {
            var result = new List<Column>();
            try
            {
                ConnectionHandler.Instance.Connection.Open();
                GetColumns(tableName, result);
                GetPkColumns(tableName, result);
            }
            catch (Exception e)
            {
                System.Windows.Forms.MessageBox.Show(e.ToString());
            }
            finally
            {
                ConnectionHandler.Instance.Connection.Close();
            }

            return result;
        }

        private static void GetColumns(string tableName, List<Column> result)
        {
            using (var cmd = DataDictionaryCommands.GetSelectColumnsCommand(tableName))
            {
                using (var rdr = cmd.ExecuteReader())
                {
                    while (rdr.Read())
                    {
                        var col = new Column(rdr[0].ToString());
                        var type = rdr[1].ToString();

                        if (type == "VARCHAR2")
                        {
                            col.DataType = "string";
                            col.MaxLen = Convert.ToInt16(rdr[2]);
                        }
                        else if (type == "DATE" || type.StartsWith("TIMESTAMP"))
                            col.DataType = "DateTime";
                        else if (type == "BLOB")
                            col.DataType = "byte[]";
                        else if (type == "NUMBER")
                            col.DataType = "int";

                        col.Mandatory = rdr[3].ToString() == "N";

                        result.Add(col);
                    }
                }
            }
        }

        private static void GetPkColumns(string tableName, List<Column> result)
        {
            using (var cmd = DataDictionaryCommands.GetSelectPkColumnsCommand(tableName))
            {
                using (var rdr = cmd.ExecuteReader())
                {
                    while (rdr.Read())
                    {
                        var pkColumnName = rdr[0].ToString();
                        var pkcolumn = result.Find(p => p.ColumnName == pkColumnName);
                        if (pkcolumn != null)
                            pkcolumn.PrimaryKey = true;
                    }
                }
            }
        }
    }
}
